/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.sanerzone.smscenter.modules.sms.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sanerzone.smscenter.biz.config.PhoneConfigInterfaceImpl;
import com.sanerzone.smscenter.biz.iface.CachRefreshInterface;
import com.sanerzone.smscenter.biz.iface.PhoneConfigInterface;
import com.sanerzone.smscenter.modules.sms.dao.SmsPhoneBlacklistDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sanerzone.jeebase.common.config.Global;
import com.sanerzone.jeebase.common.persistence.Page;
import com.sanerzone.jeebase.common.web.BaseController;
import com.sanerzone.jeebase.common.utils.StringUtils;
import com.sanerzone.smscenter.modules.sms.entity.SmsPhoneBlacklist;
import com.sanerzone.smscenter.modules.sms.service.SmsPhoneBlacklistService;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 系统黑名单Controller
 * @author zhukc
 * @version 2017-06-26
 */
@Controller
@RequestMapping(value = "${adminPath}/sms/smsPhoneBlacklist")
public class SmsPhoneBlacklistController extends BaseController {
	@Autowired
	private CachRefreshInterface cachRefreshInterface;
	@Autowired
	private SqlSessionFactoryBean sqlSessionFactoryBean;

	@Autowired
	private SmsPhoneBlacklistService smsPhoneBlacklistService;
	
	@ModelAttribute
	public SmsPhoneBlacklist get(@RequestParam(required=false) String id) {
		SmsPhoneBlacklist entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = smsPhoneBlacklistService.get(id);
		}
		if (entity == null){
			entity = new SmsPhoneBlacklist();
		}
		return entity;
	}
	
	@RequiresPermissions("sms:smsPhoneBlacklist:view")
	@RequestMapping(value = {"list", ""})
	public String list(SmsPhoneBlacklist smsPhoneBlacklist, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SmsPhoneBlacklist> page = smsPhoneBlacklistService.findPage(new Page<SmsPhoneBlacklist>(request, response), smsPhoneBlacklist);
		model.addAttribute("page", page);
		return "modules/sms/smsPhoneBlacklistList";
	}

	@RequiresPermissions("sms:smsPhoneBlacklist:view")
	@RequestMapping(value = "form")
	public String form(SmsPhoneBlacklist smsPhoneBlacklist, Model model) {
		model.addAttribute("smsPhoneBlacklist", smsPhoneBlacklist);
		return "modules/sms/smsPhoneBlacklistForm";
	}
	//batchForm
	@RequiresPermissions("sms:smsPhoneBlacklist:view")
	@RequestMapping(value = "batchForm")
	public String form() {
		return "modules/sms/smsPhoneBlacklistBatch";
	}
	//batchSave
	@RequiresPermissions("sms:smsPhoneBlacklist:edit")
	@RequestMapping(value = "batchFormSave")
	public String batchSave(MultipartFile file,String level,Model model){
		String message="";
		SqlSession sqlSession=null;
		int index=0;
		int indexExsit=0;
		boolean errorFlag=false;
		Map<String,String> phoneMap=new HashMap<>( );
		try{

			String fileName=file.getOriginalFilename();
			StringBuffer sb=new StringBuffer( );

			if (fileName.contains(".txt")) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
				String line=null;
				SqlSessionFactory sqlSessionFactory= sqlSessionFactoryBean.getObject();
				sqlSession=sqlSessionFactory.openSession();
				SmsPhoneBlacklistDao smsPhoneBlacklistDao= sqlSession.getMapper( SmsPhoneBlacklistDao.class );
				while ((line=reader.readLine())!=null){
					line=line.trim();
					String regex = "^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$";
					Pattern pattern = Pattern.compile( regex );
					Matcher matcher = pattern.matcher( line );
					if (matcher.matches()||line.length()==7||line.length()==6){
						//如果该条号码记录不存在
						if(smsPhoneBlacklistDao.findBlackListByPhone( line )==null){
							SmsPhoneBlacklist smsPhoneBlacklist= new SmsPhoneBlacklist( );
							smsPhoneBlacklist.setPhone( line );
							smsPhoneBlacklist.setLevel( level );
							smsPhoneBlacklist.setCreateDate( new Date( ) );
							//如果符合格式
							int result=smsPhoneBlacklistDao.insert(smsPhoneBlacklist );
							if (result==1){
								index++;
								phoneMap.put( line,level );

								if (index%500==0){
									sqlSession.commit();
									cachRefreshInterface.configSysBlack( phoneMap );
									phoneMap.clear();
								}
							}
						}else{
							indexExsit++;
						}
					}
				}
			}else{
				message="非文本类型";
			}
		}catch (Exception e){
			errorFlag=true;

		}finally {
			if (sqlSession!=null){
				sqlSession.close();
			}
		}
		if (errorFlag){
			message="读取文件流错误，请重试";
		}else{
			message="成功导入"+index+"个黑名单号码,等级为"+level+",其中库中已经存在的号码数量为"+indexExsit;
		}

		model.addAttribute( "message",message );


		return "modules/sms/smsPhoneBlacklistBatch";
	}





	@RequiresPermissions("sms:smsPhoneBlacklist:edit")
	@RequestMapping(value = "save")
	public String save(SmsPhoneBlacklist smsPhoneBlacklist, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, smsPhoneBlacklist)){
			return form(smsPhoneBlacklist, model);
		}
		smsPhoneBlacklistService.save(smsPhoneBlacklist);
		Map<String,String> map=new HashMap<>( );
		map.put( smsPhoneBlacklist.getPhone(),smsPhoneBlacklist.getLevel() );
		cachRefreshInterface.configSysBlack(map  );
		addMessage(redirectAttributes, "保存系统黑名单成功");

		return "redirect:"+Global.getAdminPath()+"/sms/smsPhoneBlacklist/?repage";
	}

	@RequiresPermissions("sms:smsPhoneBlacklist:edit")
	@RequestMapping(value = "delete")
	public String delete(SmsPhoneBlacklist smsPhoneBlacklist, RedirectAttributes redirectAttributes) {
		smsPhoneBlacklistService.delete(smsPhoneBlacklist);
		cachRefreshInterface.configSysBlacklist( 2,smsPhoneBlacklist.getPhone(),null,null );
		addMessage(redirectAttributes, "删除系统黑名单成功");
		return "redirect:"+Global.getAdminPath()+"/sms/smsPhoneBlacklist/?repage";
	}

}